package cn.swust.functest;

import javax.swing.JTextField; 
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class RegularTextField extends JTextField {
	 
	private static final long serialVersionUID = 1L;//此包是关于输入数据的判定
	
	private String regularText = ""; 
	
	public String getRegularText() {
		return regularText;
	} 

	public void setRegularText(String regularText) {
		this.regularText = regularText;
	}
	
	FocusListener focusListener = new FocusListener(){
		public void focusGained(FocusEvent e) {
			e.getComponent().setForeground(Color.BLUE);//控制输入时数字的颜色
		}

		public void focusLost(FocusEvent e) {
			RegularTextField tf = (RegularTextField)e.getComponent();
			checkData(tf,  tf.getRegularText());
		}
		
	};

	public RegularTextField() {
		this.addFocusListener(focusListener);
	}
	
	
	private boolean checkData(JTextField tf, String regular)//？？？？？
	{
		String code = tf.getText();
		if (code == null){
			tf.setForeground(Color.RED); 
			return false;
		}
		
		if(regular.equals("")){
			tf.setForeground(Color.GREEN);
			return true;
		}
		if(code.matches(regular)){
			tf.setForeground(Color.GREEN);
			return true;
		}
		else{
			tf.setForeground(Color.RED); 
			return false;
		} 
	}
	
	public boolean availability()//判断
	{
		return checkData(this, this.getRegularText());
	}
	

}
